import pprint 
from time import gmtime, strftime 
import  pywapi
import string 
import re 
import socket   # necessary for socket stuff (duh, (c :)
import sys      # necessary to handle command-line arguments
import time, thread
import ctypes 
import feedparser 
import urllib
import  pywapi
import string 

from BeautifulSoup import BeautifulSoup 


#main skypy bot class
class SkyPyBot(object):
    
    def __init__(self):
        self.cmd = {'#POGODA': {
                   'f': self.pogoda,
                   'd': 'Weather from Cracow (lots of TODO here)'
                   },                 
        '#EUREST': {
                   'f': self.eurest,
                   'd': 'Onet Eurestu Menu',
                   },
        '#HELP': {
                   'f': self.helpsk,
                   'd': 'You are looking at it :D',
                   },
        '#ONET': {
                   'f': self.onet,
                   'd': 'Onet news',
                   },                   
        '#GAZETA': {
                   'f': self.gazeta,
                   'd': 'Gazeta.pl news',
                   },
        '#TVN24' : {
                   'f': self.tvn24,
                   'd': 'TVN24 news',
                   },   
        '#FILMWEB' :{
                   'f': self.filmweb,
                   'd': 'Filmweb.pl news',
                   },   
        '#LG' :{
                   'f': self.live,
                   'd': 'Live news from gazeta.pl, usage #LG@link',
                   },   
        '#STOPLG' :{
                   'f': self.livestop,
                   'd': 'STOP live sg, not working!!!',
                   },                                                                                
        }
        
        pass
    
    def __del__(self):
        pass

    def helpsk(self, msg,chat):
        ret = "SkyPyBot v0.1 \n"
        ret += "Aviable commands:\n\n" 
        for c in self.cmd:
           ret += c + "\t\t- " + self.cmd[c]['d'] + "\n"   
        return ret 
 
    def pogoda(self,msg,chat):
       google_result = pywapi.get_weather_from_google('Cracow, Poland','PL')
       return "Google says: " + string.lower(google_result['current_conditions']['condition']) + ", "  + google_result['current_conditions']['wind_condition']   + ", "  + google_result['current_conditions']['humidity']   + ", " + google_result['current_conditions']['temp_c'] + "C w Krakowie.\n\n"
      
    def OnMessageStatus(self, Message, Status):
        if Status == 'RECEIVED':
            print(str(Message.Timestamp) + '-' + Message.ChatName + '@' + Message.FromDisplayName + ': ' + Message.Body)        
            for c in self.cmd:
               if re.search('^'+c,Message.Body):
                  try: 
                     Message.Chat.SendMessage(self.cmd[c]['f'](Message,Message.Chat))
                  except Exception, err:
                     Message.Chat.SendMessage("Cmd ERROR!  %s" %err)
        if Status == 'SENT':
            print(str(Message.Timestamp) + '-' + Message.ChatName + '@' + Message.FromDisplayName + ': ' + Message.Body);
            for c in self.cmd:
               if re.search('^'+c,Message.Body):
                  try: 
                     Message.Chat.SendMessage(self.cmd[c]['f'](Message,Message.Chat))
                  except Exception, err:
                     Message.Chat.SendMessage("Cmd ERROR! %s" %err)
    
        def pogoda(self,msg,chat):
           google_result = pywapi.get_weather_from_google('Cracow, Poland','PL')
           return "Google says: " + string.lower(google_result['current_conditions']['condition']) + ", "  + google_result['current_conditions']['wind_condition']   + ", "  + google_result['current_conditions']['humidity']   + ", " + google_result['current_conditions']['temp_c'] + "C w Krakowie.\n\n"
           
    def rss(self,link,chat):
        d = feedparser.parse(link)
        ret = '' 
        i = 0
        for e in d['entries']:
           ret += " - "  + e.title + " - " + e.link + "\n"
           i = i + 1 
           if i == 10:
              return ret  
        return ret 
        
    def eurest(self,msg,chat) :
       f = urllib.urlopen("http://onet.eurest.pl/")
       s = f.read()
       f.close()
       soup = BeautifulSoup(s)
       ret = ''
       f = soup.findAll(attrs={"class" : "pozycjamenu"})  
       for tag in f:
          for tr in tag:          
             for td in tr:
               if td.string != ' PLN':
                   ret += " - " + td.string + "\n"
       f = soup.findAll(attrs={"class" : "cpromocjan"})  
       for tag in f:
           ret +=  " - Polecamy: " + tag.string
       return ret    
    
    def onet(self,msg,chat):
        return self.rss("http://wiadomosci.onet.pl/2,kategoria.rss", None)
       
    def gazeta(self,msg,chat): 
        return self.rss("http://rss.gazeta.pl/pub/rss/wiadomosci.xml", None) 
     
    def tvn24(self,msg,chat): 
        return self.rss("http://www.tvn24.pl/najnowsze.xml", None)
    
    def filmweb(self,msg,chat): 
        return self.rss("http://www.filmweb.pl/feed/news/type/news ", None)
    
    def livegw(self,url,chat):
    
        last = ""
        print "Downloading url:" + str(url)
        pid = os.getpid()
        while True:
            f = urllib.urlopen(url)
            s = f.read()
            f.close()
            soup = BeautifulSoup(s)
            t = soup.findAll(id="artykul")
            d = str(t).split("<br />")
            text = d[2].replace("<b>","")
            text = text.replace("</b>"," - ")
            
            if(last != text):
               print "[" + str(pid) + "] " + str(text)
               if chat: 
                  chat.SendMessage("[" + str(pid) + "] " + text)
            last = text         
            time.sleep(5)
        
    def live(self,msg,chat):   
        try:
            d = msg.Body.split('@')
        except:
            d = msg.split('@')
        thread.start_new_thread(self.livegw,(d[1],chat,))
        time.sleep(1)
        return "Live thread started..."
        
    
    def livestop(self,msg,chat):
        try:
            d = msg.Body.split(':')
        except:
            d = msg.split(':')
        
        ctypes.windll.kernel32.TerminateProcess(int(d[1]), -1)
        return "Stoping pid str(" + d[1]+ ")? "
    